﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Timers;


namespace Signage01
{
    class ResourceTimer
    {
        private Canvas canvasToAdd;

        public Canvas CanvasToAdd
        {
            get { return canvasToAdd; }
            set { canvasToAdd = value; }
        }
        private Resource resourceToAdd;

        public Resource ResourceToAdd
        {
            get { return resourceToAdd; }
            set { resourceToAdd = value; }
        }

        private Rectangle rectangleToFill;

        public Rectangle RectangleToFill
        {
             get { return rectangleToFill; }
             set { rectangleToFill = value; }
        }
        public MediaElement resourceMediaElement=null;
        VisualBrush myVisualBrush;
        ImageBrush backBrush;
        public DispatcherTimer timerStart;
        //private Timer timerStart;
        public DispatcherTimer timerEnd;
        //private Timer timerEnd;

        private bool flagTimer = true;
        private bool imageLoaded = false;
        private TimelineComponent timelineComponent;
        private DateTime dateTimeFirst, dateTimeSecond;
        private double passedSecond;

        public ResourceTimer(Canvas canvas, Resource resource, Rectangle rect, TimelineComponent timelineComponent)
        {
            this.canvasToAdd = canvas;
            this.resourceToAdd = resource;
            this.rectangleToFill = rect;
            this.timelineComponent = timelineComponent;
            //if (isResourceVideo())
            {
                //resourceMediaElement = new MediaElement();
                //resourceMediaElement.LoadedBehavior = MediaState.Manual;
                //resourceMediaElement.UnloadedBehavior = MediaState.Manual;
                
            }

            
            initializeTimer();
        }
        
        private void initializeTimer()
        {            
            timerStart = new DispatcherTimer();            
            //timerStart = new System.Timers.Timer(this.resourceToAdd.Offset*1000);
            //timerStart.SynchronizingObject = this;
            timerStart.Interval = TimeSpan.FromSeconds(this.resourceToAdd.Offset);
            timerStart.Tick += timer_Tick_start;
            //end timer
            timerEnd = new DispatcherTimer();
            //timerEnd = new Timer((this.resourceToAdd.Offset + this.resourceToAdd.Duration)*1000);
            timerEnd.Interval = TimeSpan.FromSeconds(this.resourceToAdd.Offset + this.resourceToAdd.Duration);
            timerEnd.Tick += timer_Tick_end;
            //Thread.Sleep(this.resourceToAdd.Offset * 1000);
            
            timerStart.IsEnabled = true;
            //Console.WriteLine("timer start started for resource:" + resourceToAdd.LocalFile.FileName);
            timerEnd.IsEnabled = true;
            //Console.WriteLine("timer stop started for resource:" + resourceToAdd.LocalFile.FileName);
            dateTimeFirst = DateTime.Now;
        }

        void timer_Tick_start(object sender, EventArgs e)
        {
            addResourceToRectangle();
            //Console.WriteLine(resourceToAdd.LocalFile.FileName + " added");
            timerStart.IsEnabled = false;
            //timerStart = null;
        }

        void timer_Tick_end(object sender, EventArgs e)
        {
            removeResourceToRectangle();
            timerEnd.IsEnabled = false;
            this.timelineComponent.deleteResourceTimer(this);
            
        }
        public void addResourceToRectangle()
        {            
            {
                rectangleToFill.Opacity = 1;
                if (isResourceImage())
                {
                    backBrush = new ImageBrush();
                    backBrush.ImageSource =
                        new BitmapImage(
                            new Uri(System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\" + resourceToAdd.LocalFile.FileName + "." + resourceToAdd.LocalFile.FileExt, UriKind.Absolute)
                        );
                    backBrush.Viewport = new Rect(0, 0, 1, 1);
                    backBrush.TileMode = TileMode.None;

                    rectangleToFill.Fill = backBrush;
                    imageLoaded = true;
                }
                else if (isResourceVideo())
                {
                    resourceMediaElement = new MediaElement();
                    resourceMediaElement.LoadedBehavior = MediaState.Manual;
                    resourceMediaElement.UnloadedBehavior = MediaState.Manual;
                    resourceMediaElement.Source = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + "Resources\\" + resourceToAdd.LocalFile.FileName + "." + resourceToAdd.LocalFile.FileExt, UriKind.Absolute);
                    //resourceMediaElement.LoadedBehavior = MediaState.Manual;
                    resourceMediaElement.Play();
                    myVisualBrush = new VisualBrush();
                    myVisualBrush.Visual = resourceMediaElement;
                    rectangleToFill.Fill = myVisualBrush;
                    flagTimer = false;
                }
            }
            //);
        }
        public void removeResourceToRectangle()
        {
            //rectangleToFill.Fill = Brushes.AntiqueWhite;
            rectangleToFill.Opacity = 0;            
            resourceMediaElement = null;
            myVisualBrush = null;
            backBrush = null;
            imageLoaded = false;
        }

        private bool isResourceVideo()
        {
            List<string> listVideoExtention = new List<string>();
            listVideoExtention.Add("flv");
            listVideoExtention.Add("mp4");
            listVideoExtention.Add("avi");

            foreach (string tempExt in listVideoExtention)
            {
                if (resourceToAdd.LocalFile.FileExt.EndsWith(tempExt))
                {
                    return true;
                }
            }

            return false;
        }

        private bool isResourceImage()
        {
            List<string> listImageExtention = new List<string>();
            listImageExtention.Add("jpg");
            listImageExtention.Add("jpeg");
            listImageExtention.Add("png");
            listImageExtention.Add("bmp");

            foreach (string tempExt in listImageExtention)
            {
                if (resourceToAdd.LocalFile.FileExt.EndsWith(tempExt))
                {
                    return true;
                }
            }
            return false;
        }

        // resume
        public void resume()
        {            
            // end timer if

            if (null != resourceMediaElement)
            {
                try
                {
                    //resourceMediaElement.Clock = null;
                    resourceMediaElement.Play();

                    //Console.WriteLine("media resumed for " + resourceToAdd.LocalFile.FileName );
                    //resourceMediaElement.Position = TimeSpan.FromSeconds(20);
                }
                catch (Exception ex)
                {
                    //Console.WriteLine("from resourcetimer: " + ex.ToString());
                }
                if (timerEnd.IsEnabled == false)
                {
                    timerEnd.Interval = timerEnd.Interval - TimeSpan.FromSeconds(passedSecond);
                    timerEnd.IsEnabled = true;
                    dateTimeFirst = DateTime.Now; 
                    //timerEnd.IsEnabled = true;
                }
            }
            else
            {
                if (imageLoaded)
                {
                    if (timerEnd.IsEnabled == false)
                    {
                        timerEnd.Interval = timerEnd.Interval - TimeSpan.FromSeconds(passedSecond);
                        timerEnd.IsEnabled = true;
                        dateTimeFirst = DateTime.Now; 
                    }
                }
                else
                {
                    if (timerStart != null)
                    {
                        if (timerStart.IsEnabled == false)
                        {
                            timerStart.Interval = timerStart.Interval - TimeSpan.FromSeconds(passedSecond);
                            timerStart.IsEnabled = true;

                            //Console.WriteLine("timer resumed for " + resourceToAdd.LocalFile.FileName);
                        }
                    }
                    if (timerEnd != null)
                    {
                        if (timerEnd.IsEnabled == false)
                        {
                            timerEnd.Interval = timerEnd.Interval - TimeSpan.FromSeconds(passedSecond);
                            timerEnd.IsEnabled = true;
                        }
                    }
                    dateTimeFirst = DateTime.Now; 
                }
            }
            // end media element if 

            
        }

        //pause

        public void pause()
        {
            if (null!=resourceMediaElement && resourceMediaElement.IsLoaded == true)
            {
                try
                {
                    //resourceMediaElement.Clock = null;                        
                    resourceMediaElement.Pause();

                    //Console.WriteLine("media paused for " + resourceToAdd.LocalFile.FileName);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("from resourcetimer: " + ex.ToString());
                }
                if (timerEnd.IsEnabled)
                {
                    timerEnd.IsEnabled = false;
                    dateTimeSecond = DateTime.Now;
                    passedSecond = (dateTimeSecond - dateTimeFirst).TotalSeconds;
                }
            }
            else
            {
                if (imageLoaded)
                {
                    if (timerEnd.IsEnabled)
                    {
                        timerEnd.IsEnabled = false;
                    }
                }
                else
                {
                    if (timerStart.IsEnabled)
                    {
                        timerStart.IsEnabled = false;                                                
                                                
                    }
                    if (timerEnd.IsEnabled)
                    {
                        timerEnd.IsEnabled = false;                        
                    }
                }
                dateTimeSecond = DateTime.Now;
                passedSecond = (dateTimeSecond - dateTimeFirst).TotalSeconds;
            }

        }
    }
}
